package com.erp.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author lqa
 * @Date 2022-04-27 14:26:45
 */
public class VerifyCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 防止浏览器缓存
        resp.setDateHeader("Expires", -1);
        resp.setHeader("Cache-Control", "no-Cache");
        resp.setHeader("pragma", "no-Cache");
        // 定义验证码的宽高
        int width = 100;
        int height = 38;
        // 随机数数组
        char[] codeChar = "01234567689".toCharArray();
        // 定义一个存储随机数的一个临时变量
        String captch = "";
        // 创建一个随机类
        Random random = new Random();
        // 生成一张图片
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 绘制距行
        Graphics graphics = img.getGraphics(); // 绘制环境对象
        graphics.setColor(Color.gray); // 设置背景色
        graphics.fillRect(0, 0, width, height);

        // 生成验证码图片
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(codeChar.length); // 随机的一个数组下标
            // 设置字体颜色
            graphics.setColor(new Color(random.nextInt(110), random.nextInt(150), random.nextInt(200)));
            // 每个字符的宽间距，高度
            graphics.drawString(codeChar[index] + "", (i * 20) + 15, 25);
            captch += codeChar[index];

        }
        // 把验证码存到session中
        req.getSession().setAttribute("codes", captch);
        // 用ImageIo输出图片
        ImageIO.write(img, "jpg", resp.getOutputStream());


    }

}
